<template>
  <div>
    <!---搜索表单-->
    <div class="search-div">
      <el-form label-width="70px" size="small">
        <el-row>
          <el-col :span="12">
            <el-form-item label="关键字">
              <el-input
                style="width: 100%"
                v-model="searchObj.keyword"
                placeholder="用户名、姓名、手机号码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="date"
                type="daterange"
                range-separator="To"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="display:flex">
          <el-button type="primary" @click="handleSeachSysUsers" size="small">
            搜索
          </el-button>
          <el-button size="small" @click="handleClear">重置</el-button>
        </el-row>
      </el-form>
    </div>

    <!--添加按钮-->
    <div class="tools-div">
      <el-button type="success" @click="handleShowSavaUserDialog" size="small">
        添 加
      </el-button>
    </div>
    <!--新增用户对话框-->
    <el-dialog v-model="dialogVisible" :title="title" width="40%">
      <el-form :model="sysUser" label-width="120px">
        <el-form-item label="用户名">
          <el-input v-model="sysUser.userName" />
        </el-form-item>
        <el-form-item v-if="!sysUser.id" label="密码">
          <el-input v-model="sysUser.password" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="sysUser.name" />
        </el-form-item>
        <el-form-item label="手机">
          <el-input v-model="sysUser.phone" />
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8501/admin/system/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :headers="headers"
          >
            <img v-if="sysUser.avatar" :src="sysUser.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="sysUser.description" />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :disable="saveSysUserFlag"
            @click="handleSaveOrUpdateSysUser"
          >
            提交
          </el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!---数据表格-->
    <div>
      <el-table :data="list" style="width: 100%">
        <el-table-column type="index" label="编号" width="50" />
        <el-table-column prop="userName" label="用户名" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="phone" label="手机" />
        <el-table-column prop="avatar" label="头像" #default="scope">
          <img :src="scope.row.avatar" width="50" />
        </el-table-column>
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="status" label="状态" #default="scope">
          {{ scope.row.status == 1 ? '正常' : '停用' }}
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" align="center" width="280">
          <template #default="scope">
            <el-button
              type="primary"
              @click="handleShowUpdateSysUserDialog(scope.row)"
              size="small"
            >
              修改
            </el-button>
            <el-button
              @click="handleDelete(scope.row)"
              type="danger"
              size="small"
            >
              删除
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="handleShowAssignRoleDialog(scope.row)"
            >
              分配角色
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--分页导航-->
    <div>
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[1, 2, 3, 4, 5]"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!--分配角色对话框-->
    <div>
      <el-dialog v-model="assignRoledialogVisible" title="分配角色">
        <el-form>
          <el-form-item label="用户名" label-width="120px">
            <el-input v-model="userName" :disabled="true" />
          </el-form-item>
          <el-form-item label="角色列表" label-width="120px">
            <el-checkbox-group v-model="checkedRoleIds">
              <el-checkbox
                v-for="sysRole in sysRoles"
                :key="sysRole.id"
                :label="sysRole.id"
                :checked="sysRole.checked"
              >
                {{ sysRole.roleName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="assignRoledialogVisible = false">取消</el-button>
            <el-button type="primary" @click="doAssign()">
              提交
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { GetAllSysRoles } from '@/api/sysrole'
import {
  GetSysUserPage,
  DeleteSysUser,
  SaveSysUser,
  GetSysUserById,
  UpdateSysUser,
  FileUpload,
  AssignRoleToUser,
} from '@/api/sysUser'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useApp } from '@/pinia/modules/app'

/*分配角色 */
let userName = ref('')
let checkedRoleIds = ref([])
let assignRoledialogVisible = ref(false)
let sysRoles = ref([])
let userId = ref(0)

//分配角色的对话框提交按钮事件
const doAssign = () => {
  const { code, message } = AssignRoleToUser(userId.value, checkedRoleIds.value)
  assignRoledialogVisible.value = false
  fetchData()
}
//显示分配角色的对话框
const handleShowAssignRoleDialog = async row => {
  userId.value = row.id
  userName.value = row.userName
  sysRoles.value = []
  checkedRoleIds.value = []
  //查询所有的角色列表回显
  const { data } = await GetAllSysRoles(row.id)
  sysRoles.value = data
  assignRoledialogVisible.value = true
}

// 从pinia中获取token，在进行文件上传的时候将token设置到请求头中
const headers = {
  token: useApp().authorization.token,
}
// 图像上传成功以后的事件处理函数
const handleAvatarSuccess = (response, uploadFile) => {
  sysUser.value.avatar = response.data
}
//搜索表单的参数
const searchObj = ref({
  keyword: '',
  createTimeStart: '',
  createTimeEnd: '',
})
let date = ref('')
// 表格数据模型
const list = ref([
  {
    id: 1,
    userName: 'admin',
    name: 'admin',
    phone: '13121034567',
    status: 1,
    createTime: '2023-05-11',
  },
  {
    id: 2,
    userName: 'admin',
    name: 'admin',
    phone: '13121034567',
    status: 1,
    createTime: '2023-05-11',
  },
])

// 分页条数据模型
const total = ref(0)
let pageNum = ref(1)
let pageSize = ref(3)
//新增用户对话框
let title = ref('新增用户')
let dialogVisible = ref(false)
//定义一个用户
let sysUser = ref({
  userName: '',
  password: '',
  name: '',
  phone: '',
  avatar: '',
  description: '',
})
//对话框提交按钮的对话状态
let saveSysUserFlag = ref(false)

//钩子函数
onMounted(() => {
  fetchData()
})
//条件查询
const handleSeachSysUsers = () => {
  //console.log(date.value[0],date.value[1],searchObj.value)
  //封装查询条件
  searchObj.value.createTimeStart = date.value[0]
  searchObj.value.createTimeEnd = date.value[1]
  fetchData()
}
//查询分页数据
const fetchData = async () => {
  const { data } = await GetSysUserPage(
    searchObj.value,
    pageNum.value,
    pageSize.value
  )
  total.value = data.total
  list.value = data.list
}
//分页导航条的事件函数
//===每条记录条数改变时回调
const handleSizeChange = () => {
  fetchData()
}
//页码改变时回调
const handleCurrentChange = () => {
  fetchData()
}
//重置条件事件函数
const handleClear = () => {
  pageNum.value = 1
  pageSize.value = 3
  searchObj.value.keyword = ''
  fetchData()
}
//删除按钮事件函数
const handleDelete = row => {
  ElMessageBox.confirm(`您确认删除【${row.userName}】吗?`, '删除用户', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      //异步请求删除id对应的角色
      const { code, message } = await DeleteSysUser(row.id)
      if (+code === 200) {
        ElMessage.success(message)
        fetchData()
      } else {
        ElMessage.error(message)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
//显示新增用户对话框按钮事件函数
const handleShowSavaUserDialog = () => {
  sysUser.value = {}
  title.value = '新增角色'
  dialogVisible.value = true
}
//新增用户对话框提交按钮的事件函数
const handleSaveSysUser = async () => {
  //防止表单重复提交
  saveSysUserFlag.value = true
  const { code, message } = await SaveSysUser(sysUser.value)
  if (+code === 200) {
    ElMessage.success('新增成功')
    //刷新页面数据
    pageNum.value = 100
    fetchData()
  } else {
    ElMessage.error(message)
  }
  //关闭对话框
  dialogVisible.value = false
  saveSysUserFlag.value = false
}
//表格 修改用户按钮弹出更新对话框事件函数
const handleShowUpdateSysUserDialog = async row => {
  const { code, message, data } = await GetSysUserById(row.id)
  if (+code === 200) {
    title.value = '修改用户'
    sysUser.value = data
    dialogVisible.value = true
  } else {
    ElMessage.error(message)
  }
}
//新增或更新提交按钮的事件函数
const handleSaveOrUpdateSysUser = () => {
  if (sysUser.value.id) {
    handleUpdateSysUser()
  } else {
    handleSaveSysUser()
  }
}
//更新用户对话框提交按钮的事件函数
const handleUpdateSysUser = async () => {
  //防止表单重复提交
  saveSysUserFlag.value = true
  const { code, message } = await UpdateSysUser(sysUser.value)
  if (+code === 200) {
    ElMessage.success('更新成功')
    //刷新页面数据
    // pageNum.value=100
    fetchData()
  } else {
    ElMessage.error(message)
  }
  //关闭对话框
  dialogVisible.value = false
  saveSysUserFlag.value = false
}
</script>

<style scoped>
.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
